using DG.Tweening;
using Hotran.Audio;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;

public class StageManager : MonoBehaviour
{
    private int currentStage = 0;

    [SerializeField] ClickArea[] belts;
    private Vector2[] beltPositions;

    [SerializeField] float beltsShuffleTime = 0.3f;
    [SerializeField] AudioClip beltsShuffleSound;

    [SerializeField] AudioClip grayscaleSound;
    [SerializeField] AudioClip grayscaleEndSound;

    private readonly WaitForSeconds waitForShuffle = new(1f);
    private readonly WaitForSeconds waitForGrayscale = new(4f);

    private void Awake()
    {
        beltPositions = new Vector2[belts.Length];
        for (int i = 0; i < belts.Length; i++)
        {
            beltPositions[i] = belts[i].transform.position;
        }
    }

    public void NextStage(UnityAction onFinish)
    {
        currentStage++;

        if (currentStage == 1)
        {
            StartCoroutine(DoShuffleBelts(onFinish));
            return;
        }

        if (currentStage == 2 || (currentStage > 2 && Random.Range(0,3) == 1))
        {
            onFinish();
            StartCoroutine(DoGrayscale());
        }
        else
            StartCoroutine(DoShuffleBelts(onFinish));
    }

    private IEnumerator DoShuffleBelts(UnityAction onFinish)
    {
        if (!Shuffle(beltPositions) && !Shuffle(beltPositions))
        {
            onFinish();
            yield break;
        }

        AudioPlayer.Instance.PlaySound(beltsShuffleSound);
        for (int i = 0; i < beltPositions.Length; i++)
        {
            belts[i].transform.DOMove(beltPositions[i], beltsShuffleTime);
        }
        yield return waitForShuffle;
        onFinish();
    }

    private IEnumerator DoGrayscale()
    {
        AudioPlayer.Instance.PlaySound(grayscaleSound);

        foreach (var belt in belts)
        {
            belt.ToggleGrayscale();
        }
        yield return waitForGrayscale;

        AudioPlayer.Instance.PlaySound(grayscaleEndSound);

        foreach (var belt in belts)
        {
            belt.ToggleGrayscale();
        }
    }

    private bool Shuffle<T>(IList<T> items)
    {
        int sameCount = 0;
        for (int i = 0; i < items.Count; i++)
        {
            var targetIndex = Random.Range(i, items.Count);
            if (targetIndex == i)
            {
                sameCount++;
                continue;
            }
            (items[i], items[targetIndex]) = (items[targetIndex], items[i]);
        }
        return sameCount != items.Count;
    }
}
